<template>
  <div class="app-container">
    <ContentWrap>
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
            <el-form-item label="设备编号" prop="terminalID">
              <el-input
                v-model="queryParams.terminalID"
                placeholder="请输入设备编号"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <!-- <el-form-item label="设备名称" prop="terminalName">
              <el-input
                v-model="queryParams.terminalName"
                placeholder="请输入设备名称"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item> -->
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <el-tabs v-model="activeName" @tab-click="handleClick" style="margin-top: -10px;">
            <el-tab-pane label="地图" name="first">
              <div style="width: 100%;" :style="getMapHeight">
                <L7Map @mapLoaded="handleMapLoaded" :zoom="15">
                  <div
                    style="position: absolute;top: 0;left: 5px;z-index: 1000;margin: 5px;padding: 5px;background-color: #FFFFFF;border: 1px solid #7cbfee;">
                    供水管网
                    <el-switch style="margin-right: 8px;"
                               v-model="pipeNetworkVisible"
                               active-color="#13ce66"
                               inactive-color="#ff4949" @change="handlePipeNetworkVisibleChange">
                    </el-switch>
                    考核表
                    <el-switch style="margin-right: 8px;"
                               v-model="khTerminalMarkerVisible"
                               active-color="#13ce66"
                               inactive-color="#ff4949" @change="handleKhTerminalMarkerVisibleChange">
                    </el-switch>
                    贸易表
                    <el-switch style="margin-right: 8px;"
                               v-model="myTerminalMarkerVisible"
                               active-color="#13ce66"
                               inactive-color="#ff4949" @change="handleMyTerminalMarkerVisibleChange">
                    </el-switch>
                    压力监测
                    <el-switch v-model="pressureTerminalMarkerVisible"
                               active-color="#13ce66"
                               inactive-color="#ff4949" @change="handlePressureTerminalMarkerVisibleChange">
                    </el-switch>
                  </div>
                </L7Map>
                <div
                  style="position: absolute;top: 10px;right: 10px;display: flex;flex-direction: column;justify-content: center;z-index: 1200;background-color: #FFFFFF;padding: 10px 20px;">
                  <div style="font-size: 18px;font-weight: bold;">大表总览</div>
                  <div style="margin: 8px 0;">大表总数：
                    <span style="color: dodgerblue;">{{
                        khTerminalDataList.length + myTerminalDataList.length + pressureTerminalDataList.length
                      }}</span>
                  </div>
                  <div>已定位数：
                    <span style="color: dodgerblue;">{{
                        getTerminalsWithPosition().length
                      }}</span>
                  </div>
                </div>
              </div>
            </el-tab-pane>

            <el-tab-pane label="表格" name="second">
              <el-table v-loading="loading" :data="realtimeGatherDataList" border :height="getAvailableHeight"
                        :default-sort="{prop: 'pressure', order: 'descending'}">
                <el-table-column type="index" width="40" align="center" label="#"/>
                <el-table-column label="设备编号" align="left" prop="terminals.terminalID"/>
                <el-table-column label="设备名称" align="left" prop="terminals.terminalName"/>
                <el-table-column label="累计流量(m³)" align="center" prop="totalFlow" width="150" sortable/>
                <el-table-column label="正向流量(m³)" align="center" prop="readNumber" width="150" sortable/>
                <el-table-column label="反转流量(m³)" align="center" prop="reverseNumber" width="150" sortable/>
                <el-table-column label="瞬时流量(m³/h)" align="center" prop="instantNumber" width="150" sortable/>
                <el-table-column label="管网压力(MPa)" align="center" prop="pressure" width="150" sortable/>
                <el-table-column label="终端电压(V)" align="center" prop="terminalVol" width="100"/>
                <el-table-column label="终端信号强度" align="center" prop="terminalCSQ" width="100"/>
                <el-table-column label="抄表时间" align="center" prop="ReadDate" width="170"/>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="70">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-info"
                      @click="handleDetailClick(scope.row)"
                      v-hasPermi="['swla2:warnInfo:edit']"
                    >详情
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>

              <pagination
                v-show="total>0"
                :total="total"
                :page-sizes="[15, 30, 45, 60]"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"
              />
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>

      <TerminalDataDetailDialog ref="refTerminalDataDetailDialog"/>
    </ContentWrap>
  </div>
</template>

<script>
import {Marker, MarkerLayer, Popup} from '@antv/l7'
import L7Map from '@/components/L7Maps/map.vue'
import RegionTree from "@/views/leakage/components/RegionTree.vue";
import {listAllTerminals} from '@/api/leakage/terminalsInfo'
import {listAllTerminalsWq} from '@/api/leakage/terminalsWq'
import {
  listRealtimeGatherData,
} from "@/api/leakage/realtimeGatherData";
import TerminalDataDetailDialog from '../../components/TerminalDataDetailDialog.vue'
import {drawWmsLayer} from "@/components/L7Maps/util";
import {listDingWeiDa} from '@/api/leakage/dingWeiDa'
import {getGisLayers} from '@/utils/wfsUtil'

export default {
  name: "index",
  components: {L7Map, RegionTree, TerminalDataDetailDialog},
  data() {
    return {
      screenHeight: null,
      mapScene: undefined,
      // 管线图层
      pipeNetworkLayers: [],
      // 管线图层是否可见
      pipeNetworkVisible: true,
      // 考核表图层
      khTerminalMarkerLayer: undefined,
      // 考核表图层是否可见
      khTerminalMarkerVisible: true,
      // 贸易表图层
      myTerminalMarkerLayer: undefined,
      // 贸易表图层是否可见
      myTerminalMarkerVisible: true,
      // 压力监测表图层
      pressureTerminalMarkerLayer: undefined,
      // 压力监测表图层是否可见
      pressureTerminalMarkerVisible: true,
      // 定位表数据
      noDataTerminalDataList: [],
      // 定位表有坐标值的数量
      noDataTerminalPointCount: 0,
      activeName: 'first',
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 考核表数据
      khTerminalDataList: [],
      myTerminalDataList: [],
      pressureTerminalDataList: [],
      // 实时数据采集（大）表格数据
      realtimeGatherDataList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        terminal: null,
        terminalID: null,
        // terminalName: null,
        TotalFlow: null,
        ReadNumber: null,
        ReverseNumber: null,
        InstantNumber: null,
        InstantVelocity: null,
        Pressure: null,
        TerminalVol: null,
        TerminalCSQ: null,
        TerminalCSQDescribe: null,
        ValveState: null,
        TerminalTime: null,
        ReadDate: null,
        WarnFlag: null,
        Warning: null,
        type: null,
        AreaID: null,
        Caliber: null,
        Frequency: null,
        ID: null
      },
      markerList1:[],
      markerList2:[],
      markerList3:[],
      clearable1:false,
      clearable2:false,
      clearable3:false,
    }
  },
  methods: {
    handleMapLoaded(scene) {
      this.mapScene = scene
      this.khTerminalMarkerLayer = new MarkerLayer();
      this.myTerminalMarkerLayer = new MarkerLayer();
      this.pressureTerminalMarkerLayer = new MarkerLayer();
      this.pipeNetworkLayers = []
      this.getList()
      getGisLayers(scene, this.pipeNetworkLayers);
      this.mapScene.on('zoomend', (e) => {
        this.changePopupShow(1);
        this.changePopupShow(2);
        this.changePopupShow(3);
      })
    },
    changePopupShow(tag){
      if(this.mapScene.getZoom()>16.5){
        tag === 1 ? this.markerList1.forEach(m => m.openPopup()) : tag === 2 ? this.markerList2.forEach(m => m.openPopup()) : this.markerList3.forEach(m => m.openPopup());
      }else{
        tag === 1 ? this.markerList1.forEach(m => m.closePopup()) : tag === 2 ? this.markerList2.forEach(m => m.closePopup()) : this.markerList3.forEach(m => m.closePopup());
      }
      if(this.clearable1){ this.markerList1.forEach(m => m.closePopup()) }
      if(this.clearable2){ this.markerList2.forEach(m => m.closePopup()) }
      if(this.clearable3){ this.markerList3.forEach(m => m.closePopup()) }
    },
    handlePipeNetworkVisibleChange(val) {
      if (val) {
        this.pipeNetworkLayers.forEach(layer => {
          layer.show()
        })
      } else {
        this.pipeNetworkLayers.forEach(layer => {
          layer.hide()
        })
      }
      console.log('handlePipeNetworkVisibleChangehandlePipeNetworkVisibleChange', this.pipeNetworkLayers)
    },
    handleKhTerminalMarkerVisibleChange(val) {
      if (val) {
        this.clearable1 = false;
        this.addTerminalMarkerToMap(1)
      } else {
        this.khTerminalMarkerLayer.clear();
        this.clearable1 = true;
      }
      this.changePopupShow(1);
    },
    handleMyTerminalMarkerVisibleChange(val) {
      if (val) {
        this.clearable2 = false;
        this.addTerminalMarkerToMap(2)
      } else {
        this.myTerminalMarkerLayer.clear();
        this.clearable2 = true;
      }
      this.changePopupShow(2);
    },
    handlePressureTerminalMarkerVisibleChange(val) {
      if (val) {
        this.clearable3 = false;
        this.addTerminalMarkerToMap(3);
      } else {
        this.pressureTerminalMarkerLayer.clear();
        this.clearable3 = true;
      }
      this.changePopupShow(3);
    },
    /** 查询实时数据采集（大）列表 */
    getList() {
      this.loading = true;
      //考核
      let khParams = {...this.queryParams,UseType:2};
      listAllTerminals(khParams).then(res => {
        this.khTerminalDataList = res.data.filter(item => item.realtimeGatherData.readDate !== null)
        this.addTerminalMarkerToMap(1)
      })
      //贸易
      let myParams = {...this.queryParams,UseType:1};
      listAllTerminals(myParams).then(res => {
        this.myTerminalDataList = res.data.filter(item => item.realtimeGatherData.readDate !== null)
        this.addTerminalMarkerToMap(2)
      })
      //压力监测
      let pressureParams = {...this.queryParams,CurrentPressure:1};
      listAllTerminals(pressureParams).then(res => {
        this.pressureTerminalDataList = res.data.filter(item => item.realtimeGatherData.readDate !== null)
        this.addTerminalMarkerToMap(3)
      })

      listRealtimeGatherData(this.queryParams).then(res => {
        this.realtimeGatherDataList = res.rows;
        this.total = res.total;
        this.loading = false;
      });
    },
    handleClick(tab, event) {
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.markerList1 = [];
      this.markerList2 = [];
      this.markerList3 = [];
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleDetailClick(terminal) {
      let allTerminals = [...this.khTerminalDataList,...this.myTerminalDataList,...this.pressureTerminalDataList];
      const targetArr = allTerminals.filter(item => item.terminalID === terminal.terminalID)
      if (targetArr && targetArr.length > 0) {
        this.$refs.refTerminalDataDetailDialog.openDialog(targetArr[0])
      }
    },
    getTerminalsWithPosition() {
      let allTerminals = [...this.khTerminalDataList,...this.myTerminalDataList];
      return allTerminals.filter(item => item.lat != null && item.lng != null)
    },
    addTerminalMarkerToMap(terminalType) {
      const that = this
      let tempList = this.khTerminalDataList;
      let tempLayer = this.khTerminalMarkerLayer;
      let tempVisible = this.khTerminalMarkerVisible;
      let markerIcon = `/images/terminal.png`;
      if(terminalType === 2){
        tempList = this.myTerminalDataList;
        tempLayer = this.myTerminalMarkerLayer;
        tempVisible = this.myTerminalMarkerVisible;
        markerIcon = `/images/terminal2.png`;
      } else if(terminalType === 3){
        tempList = this.pressureTerminalDataList;
        tempLayer = this.pressureTerminalMarkerLayer; 
        tempVisible = this.pressureTerminalMarkerVisible;
        markerIcon = `/images/wqTerminal.png`;
      }
      const terminals = tempList.filter(item => item.lat != null && item.lng != null);
      if (tempLayer) {
        tempLayer.clear()
      }  
      let point
      terminals.forEach(t => {
        point = [parseFloat(t.lng), parseFloat(t.lat)]
        const markerContent = `<div><img src="${markerIcon}" style="width: 32px;height: 32px;"></div>`
        let el = document.createElement('div')
        el.innerHTML = markerContent
        const marker = new Marker({element: el, draggable: false, offsets: [0, 0]}).setLnglat({
          lng: parseFloat(t.lng),
          lat: parseFloat(t.lat)
        })

        const data = t.realtimeGatherData
        const popup = new Popup({
          title: t.terminalName,
          lngLat: {
            lng: parseFloat(t.lng),
            lat: parseFloat(t.lat)
          },
          offsets: [0, 40],
          closeButton: false,
          html: `<div>
                  <div>瞬时流量：${data.instantNumber != null ? '<span style="color: limegreen;">' + data.instantNumber + '</span> m³/h' : '<span style="color: red;">-<span>'}</div>
                  <div>累计流量：${data.totalFlow != null ? '<span style="color: limegreen;">' + data.totalFlow + '</span> m³' : '<span style="color: red;">-<span>'}</div>
                  <div>压&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;力：${data.pressure != null ? '<span style="color: limegreen;">' + data.pressure + '</span> MPa' : '<span style="color: red;">-<span>'}</div>
                  <div>信号强度：${data.terminalCSQ != null ? '<span style="color: limegreen;">' + data.terminalCSQ + '</span>' : '<span style="color: red;">-<span>'}</div>
                  <div>更新时间：${data.ReadDate != null ? '<span style="color: limegreen;">' + data.ReadDate + '</span>' : '<span style="color: red;">-<span>'}</div>
                </div>`,
        });
        marker.setPopup(popup)

        marker.on('click', (e) => {
          that.$refs.refTerminalDataDetailDialog.openDialog(t)
          e.preventDefault()
          e.stopPropagation()
        });

        marker.on('mouseover', (e) => {
          tempLayer.getMarkers().forEach(m => m.closePopup())
          marker.openPopup()
        })

        marker.on('mouseout', (e) => {
          if(this.mapScene.getZoom() <= 16.5){
            marker.closePopup()
          }
        });

        tempLayer.addMarker(marker);
        if(terminalType === 1){ this.markerList1.push(marker); }
        if(terminalType === 2){ this.markerList2.push(marker); }
        if(terminalType === 3){ this.markerList3.push(marker); }
      })
      this.mapScene.addMarkerLayer(tempLayer);
      if (!tempVisible) {
        tempLayer.hide()
      }
      // this.mapScene.panTo(point)
    },
    drawPipeNetwork() {
      if (this.$store.getters.deptName.indexOf('增城自来水') !== -1) {
        const url1 = 'http://139.9.155.246:8088/geoserver/wms?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&FORMAT=image%2Fpng&TRANSPARENT=true&STYLES&LAYERS=zengcheng:zhucun2_pipe&exceptions=application%2Fvnd.ogc.se_inimage&SRS=EPSG%3A4326&WIDTH=521&HEIGHT=768&BBOX={bbox}'
        this.pipeNetworkLayers.push(drawWmsLayer(this.mapScene, url1))
        const url2 = 'http://139.9.155.246:8088/geoserver/wms?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&FORMAT=image%2Fpng&TRANSPARENT=true&STYLES&LAYERS=zengcheng:ningxi2_pipe&exceptions=application%2Fvnd.ogc.se_inimage&SRS=EPSG%3A4326&WIDTH=521&HEIGHT=768&BBOX={bbox}'
        this.pipeNetworkLayers.push(drawWmsLayer(this.mapScene, url2))
      }
    }
  },
  created() {
    this.screenHeight = document.body.clientHeight
  },
  computed: {
    getMapHeight() {
      const h = this.screenHeight - 192
      return {height: h + 'px'}
    },
    getAvailableHeight() {
      return this.screenHeight - 244
    },
  },
  mounted() {
    window.onresize = () => {
      this.screenHeight = document.body.clientHeight
      this.resizeAllCharts()
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .l7-popup .l7-popup-content {
  position: relative;
  padding: 16px;
  font-size: 14px;
  color: #FFFFFF;
  background: #5e72af;
  border-radius: 3px;
  -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

::v-deep .l7-popup-anchor-bottom .l7-popup-tip {
  -webkit-align-self: center;
  -ms-flex-item-align: center;
  align-self: center;
  border-top-color: #5e72af;
  border-bottom: none;
}
</style>
